<%@ page language="java" contentType="text/html; charset=UTF-8"	 pageEncoding="UTF-8"%>
<%@ include file="../include/laypublic.jsp"%>
<!DOCTYPE html>
<html>
<head>
  <title>用户管理</title>
   <style type="text/css">
  	.layui-form-select dl{
		max-height: 150px; // 原值为300，调节高度建议为50的倍数
	}
  </style>
</head>
<body>
  <div class="layui-fluid">   
    <div class="layui-card">
      <!-- 查询区域  -->
      <div id="query-form" class="layui-form layui-card-header layuiadmin-card-header-auto">
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">用户名</label>
            <div class="layui-input-inline">
              <input type="text" name="suserName" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">真实姓名</label>
            <div class="layui-input-inline">
              <input type="text" name="srealName" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">手机</label>
            <div class="layui-input-inline">
              <input type="text" name="smobile" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">角色</label>
            <div class="layui-input-inline">
              <input type="text" name="srole" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">所属公司</label>
            <div class="layui-input-inline">
              <input type="text" name="compName" placeholder="请输入" autocomplete="off" class="layui-input">
            </div>
          </div>
          <shiro:hasPermission name="LIST_OPT">
	          <div class="layui-inline">
	            <button class="layui-btn layuiadmin-btn-admin" lay-submit lay-filter="LAY-user-back-search">
	              <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>查询
	            </button>
	            <button class="layui-btn layuiadmin-btn-admin" lay-submit lay-filter="LAY-user-back-reset">
	              <i class="layui-icon layui-icon-fonts-clear  layuiadmin-button-btn"></i>重置
	            </button>
	          </div>
          </shiro:hasPermission>
        </div>
      </div>
  	  <!-- 按钮区域  -->
      <div class="layui-card-body">
        <div style="padding-bottom: 10px;">
          <shiro:hasPermission name="ADD_OPT">
          	<button class="layui-btn layuiadmin-btn-admin " data-type="add">
          	 <i class="layui-icon layui-icon-add-1 layuiadmin-button-btn"></i>新增
          	</button>
          </shiro:hasPermission>
        </div>
        <!-- 数据表单 -->
        <table id="LAY-user-back-manage" lay-filter="LAY-user-back-manage"></table>
        
        <div class="layui-form" lay-filter="add_form" id="add_form" style="padding: 20px 30px 0 0;display:none">
		    <div class="layui-form-item">
		      	<label class="layui-form-label">所属公司</label>
		      	<div class="layui-input-inline">
			      	<select  id="add_detail_select_orgId" lay-filter="add_detail_select_orgId" lay-verify="required" lay-search>
	              		<option value="">请选择</option>
			      		<c:if test="${not empty orgInfos }">
	              			<c:forEach items="${orgInfos}" var="org">
	              				<option value="${org.id }">${org.compName }</option>
		            		</c:forEach>
	              		</c:if>
              		</select>
		      	</div>
		    </div>
		   <div class="layui-form-item">
	    		<label class="layui-form-label">所属部门</label>
	      		<div class="layui-input-inline">
	      			<select  id="add_selectDept"  lay-filter="add_selectDept" lay-verify="required" lay-search>
					</select>
	      		</div>
		    </div>
		    <div class="layui-form-item">
	    		<label class="layui-form-label">人员名称</label>
	      		<div class="layui-input-inline">
	      			<select name="hrStaffId" id="add_selectStaff" lay-filter="add_selectStaff"  lay-verify="required" lay-search>
					</select>
	      		</div>
		    </div>
		    <div class="layui-form-item">
		      <label class="layui-form-label">人员工号</label>
		      <div class="layui-input-block">
		        <input type="text"  readonly="readonly" style="border:0;" id="add_staff_code" autocomplete="off" class="layui-input">
		      </div>
		    </div>
		    <div class="layui-form-item">
		      <label class="layui-form-label">用户名</label>
		      <div class="layui-input-block">
		        <input type="text" name="suserName" maxlength="20" lay-verify="required|nickname" placeholder="请输入用户名" autocomplete="off" class="layui-input">
		      </div>
		    </div>
		    <div class="layui-form-item" id="password_div">
		    	<label class="layui-form-label">密码</label>
			    <div class="layui-input-block">
			      <input type="password" name="spassword" maxlength="30" id="LAY_password" lay-verify="required|pass" placeholder="请输入密码" autocomplete="off" class="layui-input">
			    </div>
		  	</div>
		    <div class="layui-form-item" id="repass_div">
		    	<label class="layui-form-label">确认密码</label>
			    <div class="layui-input-block">
			      <input type="password" name="spassword1" maxlength="30" lay-verify="repass" placeholder="请输入确认密码" autocomplete="off" class="layui-input">
			    </div>
		  	</div>
		    <div class="layui-form-item layui-hide">
		      <input type="button" lay-submit lay-filter="add_form_submit" id="add_form_submit" value="确认">
		    </div>
	  	</div>
	  	
  		<!-- 修改密码div  -->
       	<div id="w_editpwd" lay-filter="w_editpwd" class="layui-form" style="padding: 20px 30px 0 0;display:none">
         		<input type="hidden" name="cid" />
            <div class="layui-form-item">
              <label class="layui-form-label">新密码</label>
              <div class="layui-input-inline">
                <input id="edit_password" type="password" maxlength="30" name="pasword" lay-verify="required|pass" lay-verType="tips"  autocomplete="off" class="layui-input">
              </div>
              <div class="layui-form-mid layui-word-aux">8到16个字符</div>
            </div>
            <div class="layui-form-item">
              <label class="layui-form-label">确认新密码</label>
              <div class="layui-input-inline">
                <input id="repwd" type="password" maxlength="30" name="pasword1" lay-verify="required|editrepass" lay-verType="tips" autocomplete="off" class="layui-input">
              </div>
            </div>
            <div class="layui-form-item layui-hide">
                <input type="button" lay-submit id="lay-edit-pwd-submit" lay-filter="lay-edit-pwd-submit" value="确认修改"/>
            </div>
       	</div>
        	
       	<!-- 分配角色div  -->
       	<div id="w_givenrole" lay-filter="w_givenrole" class="layui-form" style="padding: 20px 30px 0 0;display:none">
         	<input type="hidden" name="rid" />
			<input type="hidden" name="roleIds" />
         	<div id="roleTransfer" style="margin-left:31px"></div>
         	<div class="layui-form-item layui-hide">
                <input type="button" lay-submit id="lay-given-role-submit" lay-filter="lay-given-role-submit" value="确认修改"/>
            </div>
        </div>
      </div>
    </div>
  </div>

  <script>
  layui.config({
    base: '${ctx}/resources/layuiadmin/' //静态资源所在路径
  }).extend({
    index: 'lib/index' //主入口模块
  }).use(['index', 'table', 'set', 'transfer'], function(){
    var $ = layui.$
    ,form = layui.form
    ,table = layui.table;
 	// 正则校验
    form.verify({
    	 pass: [
    	    /^(?=.*?[a-z])(?=.*?[A-Z])(?=.*?\d)^.{8,16}$/
    	    ,'必须同时包含大写字母、小写字母、数字'
    	  ],
    	  editrepass: function(t){
  		  	if(t !== $("#edit_password").val()){
  				return "两次密码输入不一致";
  		  	}
  		  }
	});

    // 表单
    table.render({
      elem: '#LAY-user-back-manage'
      ,url: basePath + '/operator/queryData' //请求数据接口
      ,cols: [[
        {type: 'checkbox', fixed: 'left'}
        ,{field: 'suserName', title: '用户名'}
        ,{field: 'srealName', title: '真实姓名'}
        ,{field: 'smobile', title: '手机'}
        //,{field: 'smail', title: '邮箱'}
        ,{field: 'srole', title: '角色', templet: function(d){
      		  return d.srole||global_null_tip;
        	}
        }
        ,{field: 'compName', title: '所属公司',width:300, templet: function(d){
    		  return d.compName||global_null_tip;
    		}
        }
        ,{field: 'bisFreeze',width:80,align:'center', title: '状态', templet: function(d){
  			if(d.bisFreeze == 1){
  				return "已启用";
  			}else{return '<span class="layui-badge layui-bg-cyan">已停用</span>' ;}
	       }
	     }
        ,{title: '操作', width: 350, align:'center', fixed: 'right', templet: function(d){
      	  var optStr ="";
      	  <shiro:hasPermission name="ENABLE_OPT">
      		if(d.bisFreeze == 0){//状态为停用
				optStr += '<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="use"><i class="layui-icon layui-icon-ok"></i>启用</a>';
       		}else if(d.bisFreeze == 1){//状态为启用
       			if(d.suserName == 'admin'){
	       			optStr += '<a class="layui-btn layui-btn-disabled layui-btn-xs"><i class="layui-icon layui-icon-pause"></i>停用</a>';
       			}else{
	       			optStr += '<a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="freeze"><i class="layui-icon layui-icon-pause"></i>停用</a>';
       			}
       		}
  	  	  </shiro:hasPermission>
  	  	  <shiro:hasPermission name="DELETE_OPT">
  			 if(d.suserName == 'admin'){
  				 optStr += '<a class="layui-btn layui-btn-disabled layui-btn-xs"><i class="layui-icon layui-icon-delete"></i>删除</a>';
  	    	 }else{
  	    		 optStr += '<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>';
  	    	 }
  		  </shiro:hasPermission>
  		  <shiro:hasPermission name="ASSIGN_OPT">
  			 if(d.suserName == 'admin'){
  				if('${loginUserName}' == 'admin'){
		  		  	optStr += '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="givenRole"><i class="layui-icon layui-icon-auz"></i>分配角色</a>';
  				}else{
  				 	optStr += '<a class="layui-btn layui-btn-disabled layui-btn-xs"><i class="layui-icon layui-icon-auz"></i>分配角色</a>';
  				}
	    	 }else{
	  		  	optStr += '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="givenRole"><i class="layui-icon layui-icon-auz"></i>分配角色</a>';
	    	 } 
  		  </shiro:hasPermission>
  		  <shiro:hasPermission name="PASS_OPT">
  			 if(d.suserName == 'admin'){
		  		 optStr += '<a class="layui-btn layui-btn-disabled layui-btn-xs"><i class="layui-icon layui-icon-edit"></i>修改密码</a>';
	    	 }else{
		  		 optStr += '<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="changePwd"><i class="layui-icon layui-icon-edit"></i>修改密码</a>';
	    	 } 
  		  </shiro:hasPermission>
  		  return optStr;
        	}
        }
      ]]
      ,page: true
      ,limit: 10
    });
    
    <shiro:hasPermission name="LIST_OPT">
	    //监听搜索
	    form.on('submit(LAY-user-back-search)', function(data){
	      //执行重载
	      table.reload('LAY-user-back-manage', {page: {curr: 1},
	        where: trimData(data)
	      });
	    });
	    //重置清空
	    form.on('submit(LAY-user-back-reset)', function(data){
	    	reset_form('query-form');
	    });
    </shiro:hasPermission>
    
    // 监听操作列
    table.on('tool(LAY-user-back-manage)', function(obj){
      var data = obj.data;
      if(obj.event === 'del'){
          layer.confirm('确定删除？',{icon:3, title :'提示'}, function(index){
          	$.ajax({
  				type : 'post',
  				url : basePath + '/operator/delete?checkboxId=' + data.id,
  				success:function(result){
  					if(result.success){
  						table.reload('LAY-user-back-manage'); //数据刷新
  						layer.close(index);
  					}else{
  						layer.msg(result.msg,{icon: 7});
  				  	}
  				}
  			});
          });
      }else if(obj.event === 'use'){
    		layer.confirm('确定启用？',{icon:3, title :'提示'}, function(index){
      			$.ajax({
						type : 'post',
						url : basePath + '/operator/updateStatus?id=' + data.id,
						success:function(result){
							if(result.success){
								table.reload('LAY-user-back-manage'); //数据刷新
								layer.close(index);
							}else{
								layer.msg(result.msg,{icon: 7});
				  			}
						}
					});
      		});
  		}else if(obj.event === 'freeze'){
      		layer.confirm('确定停用？',{icon:3, title :'提示'}, function(index){
      			$.ajax({
						type : 'post',
						url : basePath + '/operator/updateStatus?id=' + data.id,
						success:function(result){
							if(result.success){
								table.reload('LAY-user-back-manage'); //数据刷新
								layer.close(index);
							}else{
								layer.msg(result.msg,{icon: 7});
				  			}
						}
					});
      		});
  		}else if(obj.event === 'edit'){
      	form.val('edit_form',data); // 填充原值
      	layer.open({
            type: 1
            ,title: '编辑用户'
            ,content: $('#edit_form')
            ,area: layui.admin.screen() < 2 ? ['80%', '500px'] : ['420px','500px']
            ,btn: ['确定', '取消']
            ,btnAlign: 'c'
            ,yes: function(index, layero){
          	  var submitID = 'edit_form_submit'
          		  ,submit = layero.contents().find('#'+ submitID);
          	  //监听提交
          	  form.on('submit('+ submitID +')', function(data){
                var field = data.field; //获取提交的字段
                //提交 Ajax 成功后，静态更新表格中的数据
                $.ajax({
                    type : 'post',
  					url : basePath + '/operator/save',
                    data: field,
  					success:function(result){
  						if(result.success){
                			table.reload('LAY-user-back-manage'); //数据刷新
                			layer.close(index); //关闭弹层
  						}else{
  							layer.msg(result.msg,{icon: 7});
  					  	}
  					}
                });
              });  
              submit.trigger('click');
            }
          });
        }else if(obj.event === 'changePwd'){//修改密码
      	  $("input[name=cid]").val(data.id);
      	  layer.open({
            	 title: '用户<' + data.srealName + '>修改密码'
                ,type: 1
                ,shadeClose: false
                ,btn: ['确定', '取消']
                ,btnAlign: 'c'
                ,area: layui.admin.screen() < 2 ? ['80%', '250px'] : ['450px', '250px']
                ,content: $('#w_editpwd')
                ,yes: function(index, layero){
              	  var submitID = 'lay-edit-pwd-submit'
              		  ,submit = layero.contents().find('#'+ submitID);
              	  	// 修改密码提交
    		    	form.on('submit('+ submitID +')', function(data){
  	  		    	$.post(basePath + '/operator/change-password', data.field, function(result) {
  	  		    		if (result.success) {
  	  						layer.msg('密码修改成功~',{icon: 1});
  	  						layer.close(index);
  	  						clean_form("w_editpwd");//清空表单
  	  					}else{
  	  						layer.msg(result.msg,{icon: 7});
  	  					}
  	  				});
  	  		    });
    		    submit.trigger('click');
                }
              });
        }else if(obj.event === 'givenRole'){//分配角色
       	  	var transfer = layui.transfer;
       	 	$("input[name=rid]").val(data.id);
       	 	var allRoleData = [];
  		  	var checkRoleData = [];
  	  	  	$.getJSON('${ctx}/operator/getAllRoleAndCheckRole?id='+data.id, function (result) {
  		    	if(result.success && result.entity != null){
  			  	allRoleData = result.entity.allRole;
  			  	if(result.entity.checkRole.length > 0){
      			  for(var i in result.entity.checkRole){
      				checkRoleData.push(result.entity.checkRole[i].id);
      			  }
  			  	}
			 	//渲染
       	    	transfer.render({
       	      		elem: '#roleTransfer'  //绑定元素
       	      		,title:['未选择角色','已选择角色']
       	      		,data: allRoleData
       	    		,parseData: function(res){
       	    	    	return {
	       	    	        "value": res.id //数据值
	       	    	        ,"title": res.sroleName //数据标题
	       	    	        ,"disabled": ""  //是否禁用
	       	    	        ,"checked": "" //是否选中
	       	    	      }
       	    	    }
		       	    ,value:checkRoleData
		       	    ,id: 'transferRender' //定义索引
       	   	   });
  		  	}
  	  		}).success(function(){})
     	  	layer.open({
           	  	title: '用户<' + data.srealName + '>分配角色'
               ,type: 1
               ,shadeClose: false
               ,btn: ['确定', '取消']
               ,btnAlign: 'c'
               ,area: layui.admin.screen() < 2 ? ['80%', '550px'] : ['538px', '550px']
               ,content: $('#w_givenrole')
               ,yes: function(index, layero){
             	  var submitID = 'lay-given-role-submit'
             		  ,submit = layero.contents().find('#'+ submitID);
             	  var transferData = transfer.getData('transferRender'); //获取右侧数据
             	  var dataArray = new Array();
             	  for(var i in transferData){
             		 dataArray.push(transferData[i].value);
             	  }
             	  $("input[name=roleIds]").val(dataArray);             	  	
             	  //分配角色提交
   		    	  form.on('submit('+ submitID +')', function(data){
 	  		    	$.post(basePath + '/operator/saveOperatorRole', data.field, function(result) {
 	  		    		if (result.success) {
 	  						layer.msg('分配角色成功~',{icon: 1});
 	  						layer.close(index);
 	  						clean_form("w_givenrole");//清空表单
 	  						table.reload('LAY-user-back-manage'); //数据刷新
 	  					}else{
 	  						layer.msg(result.msg,{icon: 7});
 	  					}
 	  				});
 	  		    });
   		    	submit.trigger('click');
               }
             });
        }
    });
    
    // 按钮事件
    var active = {
      add: function(){
        layer.open({
          type: 1
          ,title: '添加用户'
          ,content: $('#add_form')
          ,area: layui.admin.screen() < 2 ? ['80%', '500px'] : ['400px','500px']
          ,btn: ['确定', '取消']
          ,btnAlign: 'c'
          ,yes: function(index, layero){
        	  var submitID = 'add_form_submit'
            	,submit = layero.contents().find('#'+ submitID);

              //监听提交
           	  form.on('submit('+ submitID +')', function(data){
              	var field = data.field; //获取提交的字段
              	//提交 Ajax 成功后，静态更新表格中的数据
              	$.ajax({
                  	type : 'post',
					url : basePath + '/operator/save',
                  	data: field,
					success:function(result){
						if(result.success){
              				table.reload('LAY-user-back-manage'); //数据刷新
              				clean_form("add_form");//清空表单
              				layer.close(index); //关闭弹层
              			    //额外处理select
  						    $("#add_from-compId").val('');
  						    form.render("select");
						}else{
							layer.msg(result.msg,{icon: 7});
					  	}
					}
              	});
            });  
            submit.trigger('click');
          }
        }); 
      }
    }  
    // data-type事件
    $('.layui-btn.layuiadmin-btn-admin').on('click', function(){
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });
    
  	
  	// 新增-公司select监听
    form.on('select(add_detail_select_orgId)', function(data){
    	var orgId = data.value;
    	$('#add_selectDept').html('');
    	$('#add_selectStaff').html('');
    	$('#add_staff_code').val('');
    	//获取公司下的所有部门
		$.ajax({
			type : "POST", //提交方式  
			url : "${ctx}/operator/getAllDeptByOrgId",//路径  
			data : {
				"orgId" :orgId
			},//数据，这里使用的是Json格式进行传输  
			success : function(result) {//返回数据根据结果进行相应的处理 
				if(result.flag==true){
					var strBuffer = "";
					strBuffer+= '<option value="">请选择</option>';
					layui.$.each(result.depts, function(i,item){
						if(item.id != null && item.deptName != null){
							strBuffer+= '<option value='+item.id+'>'+item.deptName+'</option>';
						}
			        });
					$('#add_selectDept').append(strBuffer);
					form.render();
				}else{
					layer.msg('数据通信异常~',{icon: 0});
				}
			} 
		});
	});
  	
  	//新增-部门select监听
    form.on('select(add_selectDept)', function(data){
    	var deptId = data.value;
    	$('#add_selectStaff').html('');
    	$('#add_staff_code').val('');
    	$.ajax({
			type : "POST", //提交方式  
			url : "${ctx}/operator/getValidStaffByDept",//路径  
			data : {
				"deptId" :deptId
			},//数据，这里使用的是Json格式进行传输  
			success : function(result) {//返回数据根据结果进行相应的处理 
				if(result.flag == true){
					var strBuffer = "";
					strBuffer+= '<option value="">请选择</option>';
					layui.$.each(result.staffs, function(i,item){
						strBuffer+= '<option value='+item.staffId+'>'+item.staffName+'</option>';
			        });
					$('#add_selectStaff').append(strBuffer);
					form.render();
				}else{
					layer.msg('数据通信异常~',{icon: 0});
				}
			}  
		});
	});
  	
    //新增-人员select监听
    form.on('select(add_selectStaff)', function(data){
    	var staffId = data.value;
    	$('#add_staff_code').val('');
    	$.ajax({
			type : "POST", //提交方式  
			url : "${ctx}/operator/getStaffInfoById",//路径  
			data : {
				"staffId" :staffId
			},//数据，这里使用的是Json格式进行传输  
			success : function(result) {//返回数据根据结果进行相应的处理 
				if(result.flag == true){
					$('#add_staff_code').val(result.staffInfo.staffCode);
					form.render();
				}else{
					layer.msg('数据通信异常~',{icon: 0});
				}
			}  
		});
	});
    
  	
  });
  </script>
</body>
</html>

